<template>
<div>
  <h1>Key Ring</h1>
  <p>{{ numKeys }}</p>
  <div v-if="numKeys > 0">
    <ul>
      <li v-for="(key, index) in ssiKeystore" v-bind:key="index">
        <span>{{ key.fingerprint }}</span>&nbsp;&#45;
        <span v-if="key.pubKey && key.pubKey !== ''">********</span>
        <span v-else>NO_PUB</span>&nbsp;&#45;
        <span v-if="key.pvtKey && key.pvtKey !== ''">********</span>
        <span v-else>NO_PRIVATE</span>
      </li>
    </ul>
  </div>
  
  <div v-if="false">
    <hr />
    
    <h2>Create New Key Pair</h2>
    <p><strong>ATTENTION&#58;</strong>
      This will create a new key pair.</p>
    <button v-on:click="createKeypair()" class="danger">Create Key Pair</button>
  </div>
  
</div>
</template>

<script>
import {mapState, mapGetters, mapActions} from "vuex"

export default {
    name: "Ring",
    data() {
        return {}
    },
    computed: {
        ...mapState([
            "ssiKeystore"
        ]),
        ...mapGetters([
            "numKeys"
        ])
    },
    methods: {
        ...mapActions({
            addKeypair: "addKeypair",
        }),
        createKeypair: function() {
            //NOTE: Using a low prime 60 for performace during development!
            //NOTE: Using DH instead of RSA for now.
            //TODO: Change this to a higher number or use a key generation
            //      local service to offload to task.
            //      4096 takes forever on my system.
            const crypto = require('crypto');
            const dh = crypto.createDiffieHellman(64);
            dh.generateKeys();
            
            let keyPair = {
                fingerprint: this.getHash(dh.getPublicKey('hex'), "sha1", "hex")
                , pubKey: dh.getPublicKey('hex')
                , pvtKey: dh.getPrivateKey('hex')}
            
            console.info(keyPair)
            
            this.addKeypair(keyPair)
        },
        // getFingerprint: function(protoFingerprint) {
        //     //NOTE: Right now the creation only makes the sha1, not the last octet
        //     //https://tools.ietf.org/html/rfc4880#section-12.2
        //     //TODO: Take a look at this:
        //     //https://github.com/gnewpg/node-pgp/pull/7/commits/ace46fa5702d2cc81726608c39036667bd9a1ff1
        // },
        getHash: function(text, hType, rType) {
            try {
                const crypto = require('crypto');
                const hash = crypto.createHash(hType)
                      .update(text)
                      .digest(rType);
                return hash.toUpperCase();
            } catch (err) {
                console.error('failed to create hash');
            }
        },
    }
}

</script>
